<?php

include_once 'ZReader.php';
include_once 'ZThreadCollection.php';
include_once 'ZThreadItem.php';

class ZThreadReader extends ZReader {
    protected $cache    = 'thread';

    /**
     * Generate command string
     * @return string
     */
    public function command() {
        return sprintf('threads %s %s %s %s %s'."\r\n",
            $this->begin,
            $this->end,
            $this->timeZone,
            $this->language,
            $this->query
        );
    }

    /**
     * Parse data that receive from server to object
     * @param $callback
     * @param $state
     * @return ZThreadCollection
     */
    public function parse($callback, &$state) {
        $collections = new ZThreadCollection();

        $i = 0;

        $arr = array();

        $succeed = false;

        //Read data while not end of file
        while (!$this->eof()) {
            //Read the first block is the length of the data
            $numBytes = $this->readNum();

            if ($numBytes >= 0 && $numBytes < 0xffffffff) {
                //Read data
                if ($i == 2 || $i == 3 || $i == 5) {
                    $arr[] = $this->readNum($numBytes);
                }
                else {
                    $arr[] = $this->readStr($numBytes);
                }
                $i++;

                //Enough a item
                if ($i == 6) {
                    $threadItem = new ZThreadItem($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5]);
                    $collections->addItem($threadItem);
                    $arr = array();
                    $i = 0;
                }
                //Not succeeded
                $succeed = false;
            }
            else if ($numBytes == 0xffffffff) {
                $succeed = true;
            }
        }

        $state = $succeed ? ($collections->count()> 0 ? 1 : 0) : -1;

        return $collections;
    }

    /**
     * @param null $callback
     * @return ZThreadCollection
     * @throws Exception
     */
    public function read($callback = null) {
        return parent::read($callback);
    }
}

?>
